<template>
  <div class="cartoon-edit">
    <el-tabs v-model="state.activeName" lazy>
      <el-tab-pane label="漫画详情" name="first">
        <div class="container">
          <div class="info-box">
            <div class="info-cover">
              <img v-if="state.cartoonInfo.img_url" :src="state.cartoonInfo.img_url" alt="" />
              <img v-else src="~@/assets/images/default.jpg" alt="" />
              <!-- <img src="~@/assets/images/default.jpg" alt="" /> -->
            </div>
            <div class="info-wrap">
              <div class="comic-title">{{ state.cartoonInfo.name }}</div>
              <div class="comic-author">
                <span>作者：</span>
                <span>{{ state.cartoonInfo.author }}</span>
              </div>
              <div class="comic-author">
                <span>分类：</span>
                <el-select v-model="state.cartoonInfo.category_id" class="text-input">
                  <el-option v-for="(item, index) in categoryList" :key="index" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </div>
              <div class="comic-status">
                <span class="text">
                  阅读量:
                  <el-input v-model="state.cartoonInfo.read" class="text-input" />
                </span>
                <span class="text">
                  点赞量:
                  <el-input v-model="state.cartoonInfo.fabulous" class="text-input" />
                </span>
                <span class="text">
                  是否收费:
                  <el-select v-model="state.cartoonInfo.charge" class="text-input">
                    <el-option v-for="(item, index) in chargeArr" :key="index" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </span>
                <span class="text" v-if="state.cartoonInfo.charge == 0">
                  价格:
                  <el-input v-model="state.cartoonInfo.price" class="text-input" />
                </span>
              </div>
              <div class="comic-intro">
                <div class="title">简介：</div>
                <div class="info">
                  <el-input v-model="state.cartoonInfo.cartoon_introduction" placeholder="请输入简介内容" :rows="4"
                    type="textarea" style="width: 500px" />
                </div>
              </div>
              <div class="comic-handles">
                <el-button style="width: 120px; margin-right: 10px" type="success" round size="large"
                  @click="cartoon.editRow(state.cartoonInfo, 'editProduct')">保存漫画</el-button>
                <el-upload action="#" :on-error="imgSaveToUrl" :before-upload="beforeAvatarUpload">
                  <el-button type="primary" round size="large" style="width: 120px"> 选择封面 </el-button>
                </el-upload>
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="添加章节" name="second">
        <div class="ch-container">
          <div class="cover">
            <Upload width="148px" height="200px" @change="getImg" />
          </div>
          <div class="form-box">
            <el-form ref="ruleFormRef" :rules="rules" :model="ruleForm" label-width="120px" class="demo-ruleForm"
              status-icon>
              <div class="form-item">
                <el-form-item label="章节名称" prop="title">
                  <el-input v-model="ruleForm.title" class="text-input" />
                </el-form-item>
                <el-form-item label="章节别名" prop="title_alias">
                  <el-input type="number" :min="1" v-model="ruleForm.title_alias" class="text-input" />
                </el-form-item>
              </div>
              <div class="form-item">
                <el-form-item label="是否付费">
                  <el-select v-model="ruleForm.is_vip" class="text-input">
                    <el-option v-for="(item, index) in chargeArr" :key="index" :label="item.label" :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="价格" v-show="ruleForm.is_vip == 1" prop="price">
                  <el-input v-model="ruleForm.price" class="text-input" />
                </el-form-item>
              </div>
              <el-form-item>
                <el-button type="primary" style="margin-right: 10px" @click="submitForm(ruleFormRef)">保存章节</el-button>
                <!-- <el-button @click="importChapter">批量导入章节</el-button> -->
                <el-upload ref="importRef" accept=".xls,.xlsx " action="https://jsonplaceholder.typicode.com/posts/"
                  :on-change="importChapter" :show-file-list="false" :auto-upload="false">
                  <el-button> 批量导入章节 </el-button>
                </el-upload>
                <!-- <el-upload
                  ref="importRef"
                  accept=".xls,.xlsx "
                  action="https://jsonplaceholder.typicode.com/posts/"
                  :on-change="importChapterPage"
                  :show-file-list="false"
                  :auto-upload="false"
                  style="margin-left: 10px"
                >
                  <el-button>一键导入章节内容 </el-button>
                </el-upload> -->
              </el-form-item>
            </el-form>
          </div>
          <div class="carry-log">
            <div class="form-item">
              <p>执行日志</p>
            </div>
            <div class="form-item">
              <el-input type="textarea" v-model="state.linkLog" rows="7" disabled resize="none"></el-input>
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
    <div class="de-container">
      <div class="chapter-title">
        <div class="time">
          <span style="font-size: 24px">连载</span>
          <span class="uplate-time">{{ state.update_time }}</span>
        </div>
        <div class="btn-sort">倒叙</div>
      </div>
      <div class="chapter-list">
        <div class="chapter-box">
          <div class="chapter-item" v-for="item in state.chapterList" :key="item.chapter_id">
            <span @mouseenter="seen = true">{{ item.title }}</span>
            <!-- <el-tooltip placement="top">
              <template #content>导入章节内容 </template>
              <el-icon v-show="seen" @mouseleave="seen = false" :size="20" class="icon-item" @click="importPage(item)">
                <Plus />
              </el-icon>
            </el-tooltip> -->
            <!-- <el-icon :size="20" class="icon-item">
              <Edit />
            </el-icon> -->
            <!-- <el-icon :size="20" class="icon-item">
              <Delete />
            </el-icon> -->
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, getCurrentInstance, reactive } from 'vue'
import CartoonService from '@/service/CartoonService'
import { chargeArr } from '../ts/data'
import { ElMessage, FormInstance, FormRules, UploadFile, UploadRawFile } from 'element-plus'
import { cartoonDetail, chapter } from '@/network/model/cartoonModel'
import { ImportXlsx } from '@/hooks/utils'
import { Plus } from '@element-plus/icons-vue'
import Upload from '@/components/uoload.vue'
import * as XLXS from 'xlsx'

const ruleFormRef = ref<FormInstance>()

// @ts-ignore
const { proxy } = getCurrentInstance()
const api = proxy.$api
const cartoon = new CartoonService(api)
const props = defineProps({
  sysId: {
    type: Number,
    default: 0
  },
  categoryList: {
    type: Array,
    default: []
  }
})
console.log(props.categoryList, 'categoryList')

const state = reactive({
  cartoonInfo: {
    img_url: '',
    name: '',
    author: '',
    read: 0,
    fabulous: 0,
    charge: 0,
    price: 0,
    cartoon_introduction: ''
  },
  activeName: 'first',
  chapterList: [],
  linkLog: '',
  update_time: '2022-10-15 20:00'
})
const ruleForm = reactive({
  comic_id: props.sysId,
  cover: '',
  title: '',
  title_alias: 1,
  is_vip: 0,
  price: 0
})
const categoryInfo = reactive({
  id: 1,
  name: ''
})
let seen = ref<Boolean>(false)
const rules = reactive<FormRules>({
  title: [
    {
      required: true,
      message: '章节名称不能为空',
      trigger: 'change'
    }
  ],
  title_alias: [
    {
      required: true,
      message: '章节别名不能为空',
      trigger: 'change'
    }
  ]
})
onMounted(() => {
  init()
})
async function init() {
  const res = await cartoon.getCartoonDetail(props.sysId, 'getCartoonDetail')
  const res1 = await cartoon.getChapterAll(props.sysId, 'getChapterAll', 1)
  if (res.code == 200 && res1.code == 200) {
    state.cartoonInfo = res.data
    res1.data.forEach((item: cartoonDetail) => {
      item.create_time = item.create_time.replace('T', ' ').replace('.000Z', '')
      state.update_time = item.create_time
    })
    console.log(res1.data)

    state.chapterList = res1.data
  }
}
// 导入章节列表并上传
async function importChapter(file: File) {
  state.linkLog = ''
  try {
    let res: any = await ImportXlsx(file)
    console.log(res, 'res')
    let head = {
      章节名称: 'title',
      封面: 'cover',
      章节别名: 'title_alias',
      价格: 'price',
      是否vip: 'is_vip',
      上家ID: 'platform_chapter'
    }
    const list = res.map((item: Object) => {
      const obj: any = {}
      for (const k in item) {
        if (head[k]) {
          obj[head[k]] = item[k]
        }
      }
      return obj
    })
    const chapterLength = list.length
    for (let i = 0; i < list.length; i++) {
      const item = list[i]
      let param = { ...item }
      param.comic_id = props.sysId
      // console.log(param,'param');
      const res = await api.addChapter(param)
      if (res.code == 200) {
        state.linkLog = ``
        state.linkLog = `${i + 1}/${chapterLength}导入成功\n` + state.linkLog
      } else {
        state.linkLog = `${i + 1}/${chapterLength}导入失败,${res.msg}\n` + state.linkLog
      }
      console.log(res, '====>')
    }
  } catch (error) {
    state.linkLog = `导入失败\n` + state.linkLog
  }
  await init()
  state.linkLog = `导入完成\n` + state.linkLog
}
// 导入所有章节内容信息
async function importChapterPage(file: File) {
  try {
    let res: any = await ImportXlsx(file)
    console.log(res, 'res')
    if (state.chapterList.length == 0) {
      state.linkLog = `章节内容匹配失败，请检查是否存在章节信息\n` + state.linkLog
      return
    }
    for (let i = 0; i < state.chapterList.length; i++) {
      const item: any = state.chapterList[i]
      for (let index = 0; index < res.length; index++) {
        const v = res[index]
        if (v.chapter_id == item['platform_chapter']) {
          const param = {
            comic_id: item.comic_id,
            chapter_id: item.chapter_id,
            image: v.image,
            pageOrder: index + 1
          }
          const res1 = await api.addChapterPage(param)
          if (res1.code == 200) {
            // state.linkLog = ``
            state.linkLog = `章节内容${index + 1}/${res.length}导入成功\n` + state.linkLog
          } else {
            state.linkLog = `章节内容${index + 1}/${res.length}导入失败,${res1.msg}\n` + state.linkLog
          }
        }
      }
      state.linkLog = `第${i + 1}章节内容导入完毕\n` + state.linkLog
    }
  } catch (error) {
    state.linkLog = `导入失败\n` + state.linkLog
  }
  await init()
  state.linkLog = `导入完成\n` + state.linkLog
}
// 导入章节内容并上传
async function importPage(item: chapter) {
  console.log(item)
  try {
    const arrFileHandle = await window.showOpenFilePicker({
      types: [
        {
          accept: {
            'xlsx/*': ['.xlsx', '.xls']
          }
        }
      ],
      multiple: false
    })
    for (const fileHandle of arrFileHandle) {
      // 获取文件内容
      const fileData = await fileHandle.getFile()
      const reader = new FileReader()
      reader.readAsArrayBuffer(fileData)
      reader.onload = async (e) => {
        let data = e.target && e.target.result
        const workbook = XLXS.read(data, { type: 'binary', cellDates: true })
        const wsname = workbook.SheetNames[0]
        const outdata: any = XLXS.utils.sheet_to_json(workbook.Sheets[wsname])
        outdata.forEach(async (item1: { image: string }, index: number) => {
          const param = {
            comic_id: item.comic_id,
            chapter_id: item.chapter_id,
            image: item1.image,
            pageOrder: index + 1
          }
          const res = await api.addChapterPage(param)
          console.log(res, 'res')
          if (res.code == 200) {
            state.linkLog = ``
            state.linkLog = `${index + 1}/${outdata.length}章节内容导入成功\n` + state.linkLog
          } else {
            state.linkLog = `${index + 1}/${outdata.length}章节内容导入失败,${res.msg}\n` + state.linkLog
          }
        })
      }
    }
  } catch (error) {
    ElMessage.warning('取消导入')
  }
}
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      const res = await api.addChapter(ruleForm)
      console.log(res, '==>')
      if (res.code == 200) {
        ElMessage.success(res.msg)
        await init()
      } else {
        ElMessage.error(res.msg)
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
function getImg(url: string) {
  console.log(url, 'url')
  ruleForm.cover = url
}
const beforeAvatarUpload = (file: UploadRawFile) => {
  try {
    console.log(file, '限制操作')
    let reader = new FileReader()
    reader.onload = function (event) {
      // @ts-ignore
      let txt = event.target.result
      let img = document.createElement('img')
      // @ts-ignore
      img.src = txt
      img.onload = function () {
        console.log(img.width)
        console.log(img.height)
      }
    }
    reader.readAsDataURL(file)
    const isPNG = file.type === 'image/png'
    const isJPG = file.type === 'image/jpg'
    const isJPEG = file.type === 'image/jpeg'
    const flag = isPNG || isJPG || isJPEG
    console.log(flag, 'isJPG')
    const isLt2M = file.size / 800 / 800 < 2
    if (!flag) {
      ElMessage.error('上传商品图片只能是 PNG、JPG、JPEG 格式!')
    }
    if (!isLt2M) {
      ElMessage.error('上传商品图片大小不能超过 2MB!')
    }
    return flag && isLt2M
  } catch (error) { }
}
// 文件上传
const imgSaveToUrl = async (error: Error, file: UploadFile) => {
  try {
    console.log(file, 'file')

    const formData = new FormData()
    // @ts-ignore
    formData.append('file', file.raw)
    const res = await api.uploadFile(formData)
    console.log(res, 'res')
    if (res.code == 200) {
      state.cartoonInfo.img_url = res.data?.url
      ElMessage.success(res.msg)
    } else {
      ElMessage.error(res.msg)
    }
  } catch (error) {
    console.log(error)
    ElMessage.error('上传图片失败')
  }
}
</script>

<style lang="less" scoped>
.cartoon-edit {
  position: relative;
  top: -10px;
  height: 600px;
  overflow-y: auto;
  padding-right: 15px;

  .info-box {
    position: relative;

    .info-cover {
      position: absolute;
      display: flex;
      justify-content: center;
      align-items: center;
      top: -40px;
      width: 315px;
      height: 420px;
      border: 10px solid #fff;
      border-radius: 2px;
      box-shadow: 0 1px 10px rgba(0, 0, 0, 0.1);

      img {
        display: inline-block;
        min-width: 100%;
        width: 285px;
        height: 395px;
        background: #fff;
      }
    }

    .info-wrap {
      margin-left: 350px;

      .comic-title {
        font-size: 30px;
        font-weight: 700;
      }

      .comic-author {
        height: 28px;
        margin-top: 16px;
        line-height: 28px;
        font-size: 15px;
        color: #863b13;
      }

      .comic-status {
        margin-top: 98px;
        font-size: 14px;
        line-height: 22px;

        .text {
          margin-right: 40px;
          color: #999;

          .text-input {
            width: 100px;
          }

          b {
            color: #000;
            font-weight: 400;
          }
        }
      }

      .comic-intro {
        display: flex;
        margin-top: 12px;
        font-size: 14px;
        line-height: 22px;
        color: #999;

        .info {
          height: 100%;
          text-indent: 12px;
          color: #000;
          font-weight: 400;
          overflow: hidden;
        }
      }

      .comic-handles {
        display: flex;
        align-items: center;
        margin-top: 20px;
      }
    }
  }

  .de-container {
    margin-top: 40px;

    .chapter-title {
      display: flex;
      justify-content: space-between;
      font-size: 24px;
      line-height: 40px;
      height: 40px;
      margin-bottom: 20px;

      .time {
        .uplate-time {
          font-size: 13px;
          color: #666;
          margin-left: 10px;
        }
      }

      .btn-sort {
        font-size: 14px;
        cursor: pointer;
      }
    }

    .chapter-list {
      .chapter-box {
        display: flex;
        flex-wrap: wrap;

        // max-height: 302px;
        // overflow: hidden;
        // padding-left: 15px;
        .chapter-item {
          width: 184px;
          margin-right: 20px;
          font-size: 14px;
          height: 22px;
          margin-bottom: 10px;
          padding: 0 15px;
          line-height: 22px;
          background: #fbfbfb;
          border-radius: 2px;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;

          // cursor: pointer;
          .icon-item {
            cursor: pointer;
            height: 22px;
            line-height: 22px;
            font-weight: 500;
            color: #000;
          }
        }
      }
    }
  }

  .ch-container {
    display: flex;
    justify-content: space-between;

    .carry-log {
      width: 450px;

      .form-item {
        margin-bottom: 10px;
      }
    }

    .form-item {
      display: flex;

      .text-input {
        width: 120px;
      }
    }
  }
}

.avatar-uploader .avatar {
  width: 285px;
  height: 178px;
  display: block;
}
</style>
